package com.paw.file.util;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.math.MathUtil;
import com.paw.file.entity.FileInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 文件工具类
 *
 * @author 作者 mallplus E-mail: 951449465@qq.com
 */
@Slf4j
public class FileInfoUtil {
	private FileInfoUtil() {
		throw new IllegalStateException("Utility class");
	}

	public static FileInfo getFileInfo(MultipartFile file, byte[] bytes) {
		String md5 = fileMd5(new ByteArrayInputStream(bytes));
		FileInfo fileInfo = new FileInfo();
		fileInfo.setMd5(md5);
		fileInfo.setSrcFileName(file.getOriginalFilename());
		String contextType = FileTypeUtil.getType(new ByteArrayInputStream(bytes));
		fileInfo.setContentType(contextType);
		List<String> imgTypes = Arrays.asList("png","jpg","jpeg");
		int imgStatus = file.getContentType().startsWith("image/") || imgTypes.contains(contextType.toLowerCase()) ? 1:0;
		fileInfo.setImgStatus(imgStatus);
		fileInfo.setFileSize((int) file.getSize());
		fileInfo.setCreateTime(new Date());

		return fileInfo;
	}

	public static FileInfo getFileInfo(byte[] bytes,String originFileName, int imgStatus) {
		String md5 = fileMd5(new ByteArrayInputStream(bytes));
		FileInfo fileInfo = new FileInfo();
		fileInfo.setMd5(md5);
		fileInfo.setSrcFileName(originFileName);
		String contextType = FileTypeUtil.getType(new ByteArrayInputStream(bytes));
		fileInfo.setContentType(contextType);
		List<String> imgTypes = Arrays.asList("png","jpg","jpeg");
		fileInfo.setImgStatus(imgStatus);
		fileInfo.setFileSize(bytes.length);
		fileInfo.setCreateTime(new Date());

		return fileInfo;
	}

	private static String getFormatSize(long size){
		String result = "";
		final long vK = 10^3;
		final long vM = 10^6;
		final long vG = 10^9;
		final long vT = 10^9;
		if(size<vK){
			result = size+"B";
		}else if(size<vM){
			result = size/vK+"K";
		}else if (size<vG){
			result = size/vM+"M";
		}else {
			result = size/vG+"T";
		}

		return result;
	}

	/**
	 * 文件的md5
	 *
	 * @param inputStream
	 * @return
	 */
	public static String fileMd5(InputStream inputStream) {
		try {
			return DigestUtils.md5Hex(inputStream);
		} catch (IOException e) {
			log.error("fileMd5-error", e);
		}
		return null;
	}
}
